/*
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.jfast.framework.upload;

import cn.jfast.framework.base.cache.SDKProp;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FileRequestResolver implements FileRequest{

	private Map<String,UploadFile> fileMap = new ConcurrentHashMap<String,UploadFile>();
	private Map<String,String[]> attrMap = new ConcurrentHashMap<String,String[]>();
	private UploadFile file;

	private static final String SIGN_MULTIDATA = "multipart/form-data";

	public static boolean isMultipart(HttpServletRequest request) {
		String contentType = request.getContentType();
		if (contentType != null && !contentType.isEmpty()) {
			if (contentType.indexOf(SIGN_MULTIDATA) >= 0) {
				return true;
			}
		}
		return false;
	}

	public FileRequest resolveMultipart(HttpServletRequest request)
			throws IOException {

		if (!isMultipart(request)) {
			return this;
		}

		InputStream input = request.getInputStream();

		String charset = MultiRequestFieldAnalizer.getCharset(request);

		String boundarys = MultiRequestFieldAnalizer.getBoundaryStr(request);

		Iterator<UploadFile> uploadFiles = new UploadFileIterator(input,
				charset, boundarys.getBytes(charset));

		while (uploadFiles.hasNext()) {
			file = uploadFiles.next();
			if (null == file.getFileName()) {
				String[] tempVal = attrMap.get(file.getFieldName());
				if(null != tempVal) {
					String[] val = new String[tempVal.length + 1];
					System.arraycopy(tempVal, 0, val, 0, tempVal.length);
					val[val.length - 1] = new String(file.getFileData(), SDKProp.encoding);
					attrMap.put(file.getFieldName(), val);
				} else {
					attrMap.put(file.getFieldName(), new String[]{new String(file.getFileData(), SDKProp.encoding)});
				}
			} else {
				fileMap.put(file.getFieldName(),file);
			}
		}
		return this;
	}

	public Map<String, UploadFile> getFileMap() {
		return this.fileMap;
	}

	public Map<String, String[]> getAttrMap() {
		return this.attrMap;
	}

	public String getAttr(String fieldName) {
		String[] val = this.attrMap.get(fieldName);
		if(null == val)
			return null;
		else if(val.length > 1)
			throw new RuntimeException("param ["+fieldName+"] has multi values");
		else if(val.length == 1)
			return val[0];
		else 
			return null;
	}
	
}
